<?php 

class User{
	private $_db;
	
	public function __construct($_db){
		$this->_db = $_db; 
	}
	
	public function login($username,$password){
		$sql = 'select * from `user` where `username`=:username and `password`=:password';
		$sth = $this->_db->prepare($sql);
		$password = md5($password);
		$sth->bindParam(':password',$password);
		$sth->bindParam(':username',$username);
		$sth->execute();
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		if(empty($result)){
			return '不存在';
		}else{
			return "登录成功";
		}
	}

	public function register($username,$passwored){
		try{
			if($this->_isUsernameExits($username)){
			    throw new Exception("用户名存在");
		    }
		    if(empty($passwored)){
			    throw new Exception("密码不能为空");
		    }
		}
		catch(Exception $e){
			exit($e->getMessage().$e->getline().'line');
		}
		
		$passwored = md5($passwored);
		$created_at = time();
		$sql = 'insert into `user` (`username`,`password`,`created_at`) values (:username,:password,:created_at)';
		$sth = $this->_db->prepare($sql);
		$sth->bindParam(':username',$username);
		$sth->bindParam(':password',$passwored);
		$sth->bindParam(':created_at',$created_at);
		if($sth->execute()){
			return $this->_db->lastInsertId();
		}
	}

	/**
	 * 检查用户名是否存在
	 * @param $username
	 * @return boolean
	 */
	private function _isUsernameExits($username){
		$sql = 'select * from `user` where `username`=:username';
		$sth = $this->_db->prepare($sql);
		$sth->bindParam(':username',$username);
		$sth->execute();
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		return !empty($result);

	}
}